﻿using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Security.Principal;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using System.Web.Security;
using HelloMVC.Model;
using HelloMVC.Service;
using HelloMVC.Interface.Authorization;
using HelloMVC.Interface.Repository;

namespace HelloMVC.Controllers
{

    [HandleError]
    public class AccountController : Controller
    {

        public IFormsAuthenticationService FormsService { get; set; }
        public IMembershipService MembershipService { get; set; }
        public IAccountRepository AccountRepository { get; set; }

        public AccountController(IFormsAuthenticationService formserveice, IMembershipService membershipservice, IAccountRepository accountRepository)
        {
            FormsService = formserveice;
            MembershipService = membershipservice;
            AccountRepository = accountRepository;
        }

        // **************************************
        // URL: /Account/LogOn
        // **************************************
        public ActionResult LogOn(string returnUrl)
        {
            return View();
        }

        public ActionResult NoAccessAuthorization(string ReturnUrl)
        {
            ViewData["ReturnUrl"] = ReturnUrl;
            return View("NoAccessAuthorization");
        }

        [HttpPost]
        public ActionResult LogOn(LogInModel model, string returnUrl)
        { 
            if (ModelState.IsValid)
            {
                if (MembershipService.ValidateUser(model.UserName, model.Password))
                {
                    FormsService.SignIn(model.UserName, model.RememberMe);
                    if (!String.IsNullOrEmpty(returnUrl))
                    {
                        return Redirect(returnUrl);
                    }
                    else
                    {
                        return RedirectToAction("Index", "Home");
                    }
                }
                else
                {
                    ModelState.AddModelError("", "The user name or password provided is incorrect.");
                }
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }

        // **************************************
        // URL: /Account/Role Management
        // **************************************
        public ActionResult RoleManagement()
        {
            var users = Membership.GetAllUsers();
            ViewData["roles"] = Roles.GetAllRoles();
            return View("RoleManagement", new RoleModel());
        }

        public ActionResult AddRole(RoleModel role)
        {  
            Roles.CreateRole(role.RoleName);

            return RedirectToAction("RoleManagement", "Account");
        }


        // **************************************
        // URL: /Account/User List
        // **************************************



        // **************************************
        // URL: /Account/LogOff
        // **************************************

        public ActionResult LogOff()
        {
            FormsService.SignOut();

            return RedirectToAction("Index", "Home");
        }

        // **************************************
        // URL: /Account/Register
        // **************************************

        public ActionResult Register()
        {
            ViewData["PasswordLength"] = MembershipService.MinPasswordLength;
            return View();
        }

        [HttpPost]
        public ActionResult Register(RegisterModel model)
        {
            if (ModelState.IsValid)
            {
                // Attempt to register the user
                MembershipCreateStatus createStatus = MembershipService.CreateUser(model.UserName, model.Password, model.Email);

                if (createStatus == MembershipCreateStatus.Success)
                {
                    FormsService.SignIn(model.UserName, false /* createPersistentCookie */);
                    return RedirectToAction("Index", "Home");
                }
                else
                {
                    ModelState.AddModelError("", AccountValidation.ErrorCodeToString(createStatus));
                }
            }

            // If we got this far, something failed, redisplay form
            ViewData["PasswordLength"] = MembershipService.MinPasswordLength;
            return View(model);
        }

        // **************************************
        // URL: /Account/ChangePassword
        // **************************************

        [Authorize]
        public ActionResult ChangePassword()
        {
            ViewData["PasswordLength"] = MembershipService.MinPasswordLength;
            return View();
        }

        [Authorize]
        [HttpPost]
        public ActionResult ChangePassword(ChangePasswordModel model)
        {
            if (ModelState.IsValid)
            {
                if (MembershipService.ChangePassword(User.Identity.Name, model.OldPassword, model.NewPassword))
                {
                    return RedirectToAction("ChangePasswordSuccess");
                }
                else
                {
                    ModelState.AddModelError("", "The current password is incorrect or the new password is invalid.");
                }
            }

            // If we got this far, something failed, redisplay form
            ViewData["PasswordLength"] = MembershipService.MinPasswordLength;
            return View(model);
        }

        // **************************************
        // URL: /Account/ChangePasswordSuccess
        // **************************************

        public ActionResult ChangePasswordSuccess()
        {
            return View();
        }

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        [Authorize]
        public ActionResult UserTable()
        {
            return View("UserTable");
        }

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        [Authorize]
        [JsonFilter(Param = "datatableRequest", JsonDataType = typeof(DatatableRequestModel))]
        [AcceptVerbs(HttpVerbs.Post)]
        public JsonResult GetUserInfo(DatatableRequestModel datatableRequest)
        {
            var users = AccountRepository.GetAllUsers() ?? new List<UserModel>();

            var datatableResponse = new DatatableResponseModel
            {
                sEcho = datatableRequest.sEcho,
                iTotalDisplayRecords = users.Count,
                iTotalRecords = users.Count,
                aaData = new List<IList<String>>()
            };

            foreach (var user in users)
            {
                datatableResponse.aaData.Add(new List<String> { user.ID, user.UserName, user.Email, "Admin" });
            }

            return Json(datatableResponse);
        }

        public PartialViewResult GetUserDetailInfo(String PKID)
        {
            var UserDetail = AccountRepository.GetUserDetail(PKID);
            if (UserDetail != null)
            {
                return PartialView("UserDetail", UserDetail);
            }

            return PartialView("NoDetailNotification");
        }

    }
}
